//
//  TimePitchController.m
//  AudioKitOC
//
//  Created by Hwang on 2018/5/8.
//  Copyright © 2018年 AudioKit. All rights reserved.
//

#import "TimePitchController.h"
#import <AVFoundation/AVFoundation.h>

@interface TimePitchController ()

@property (nonatomic, strong) AVAudioEngine *engine;
@property (nonatomic, strong) AVAudioUnitTimePitch *timePitch;
@property (nonatomic, strong) AVAudioPlayerNode *player;

@end

@implementation TimePitchController
- (IBAction)overlap:(UISlider *)sender {
    _timePitch.overlap = sender.value;
}
- (IBAction)rate:(UISlider *)sender {
    _timePitch.rate = sender.value;
}
- (IBAction)pitch:(UISlider *)sender {
    _timePitch.pitch = sender.value;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    // Do any additional setup after loading the view.
    _timePitch = [[AVAudioUnitTimePitch alloc] init];
    //播放速度
    _timePitch.rate = 1.0;
    _timePitch.overlap = 32;
    //音调
    _timePitch.pitch = 0;
    
    _player = [[AVAudioPlayerNode alloc] init];
    
    NSURL *drumLoopURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"追光者" ofType:@"mp3"]];
    AVAudioFile *drumLoopFile = [[AVAudioFile alloc] initForReading:drumLoopURL error:nil];
    AVAudioPCMBuffer *_playerLoopBuffer = [[AVAudioPCMBuffer alloc] initWithPCMFormat:[drumLoopFile processingFormat] frameCapacity:(AVAudioFrameCount)[drumLoopFile length]];
    BOOL success = [drumLoopFile readIntoBuffer:_playerLoopBuffer error:nil];
    if (success) {
        
    }
    
    
    _engine = [[AVAudioEngine alloc] init];
    
    [_engine attachNode:_player];
    [_engine attachNode:_timePitch];
    [_engine connect:_player to:_timePitch format:_playerLoopBuffer.format];
    [_engine connect:_timePitch to:_engine.mainMixerNode format:_playerLoopBuffer.format];
    
    [_engine startAndReturnError:nil];
    [_player scheduleBuffer:_playerLoopBuffer completionHandler:nil];
    [_player play];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
